package com.chinasoftinc.facommon.view.login.abilitypresent;

import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.utils.TextTool;
import ohos.bluetooth.BluetoothHost;
import ohos.event.commonevent.MatchingSkills;

import com.chinasoftinc.facommon.FAConfigMgr;
import com.chinasoftinc.facommon.HilinkRegister;
import com.chinasoftinc.facommon.utils.LogUtil;
import com.chinasoftinc.facommon.view.device.ControlDeviceAbility;
import com.chinasoftinc.facommon.view.login.LoginAbility;

/**
 * @since 2022-05-09
 */
public class BleLoginAbilityPresent extends LoginAbilityPresent {
    public static final String KEY_DEVICE_ID = "deviceId";
    private final String TAG = getClass().getSimpleName();
    private static final int SOFTAP_NET_CONFIGURING = 0;

    private static final int NET_CONFIG_COMPLETED = 1;

    private BluetoothHost btHost;
    int businessStage = 0;

    public BleLoginAbilityPresent(LoginAbility ability) {
        super(ability);
        btHost = BluetoothHost.getDefaultHost(ability);
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        businessStage = intent.getIntParam("businessStage", SOFTAP_NET_CONFIGURING);
        configPageParams();
    }

    /**
     * @noinspection ConstantConditions
     */
    public void startAbility() {
        if (businessStage == NET_CONFIG_COMPLETED && !TextTool.isNullOrEmpty(deviceId)) {
            openDevicePage(KEY_DEVICE_ID, deviceId);
        }
    }

    /**
     * 打开半模态控制页面
     *
     * @param paramKey 参数键
     * @param paramValue 参数值
     */
    private void openDevicePage(String paramKey, String paramValue) {
        Intent intent = new Intent();
        intent.setParam(paramKey, paramValue);
        Operation operation = new Intent.OperationBuilder().withDeviceId("")
            .withBundleName(FAConfigMgr.get().getBundleName())
            .withAbilityName(FAConfigMgr.get().getDeviceAbilityName())
            .withFlags(Intent.FLAG_ABILITY_NEW_MISSION)
            .withFlags(Intent.FLAG_INSTALL_ON_DEMAND).build();
        intent.setOperation(operation);
        ability.startAbility(intent);
    }

    @Override
    protected void addSubscriberEvent(MatchingSkills matchingSkills) {
        matchingSkills.addEvent(BluetoothHost.EVENT_HOST_STATE_UPDATE);
    }

    @Override
    protected void onReceiveEvent(String action) {
        if (BluetoothHost.EVENT_HOST_STATE_UPDATE.equals(action)) {
            int btState = btHost.getBtState();
            LogUtil.info(TAG, "onReceiveEvent, btHost.getBtState() : " + btState);
            LogUtil.info(TAG, "onReceiveEvent, start btHost.enableBt() : ");
            if (btState == BluetoothHost.STATE_ON) {
                HilinkRegister.get().notifyEnableBluetooth();
            }
        }
    }
}
